import re
import binascii
import serial
import serial.tools.list_ports
print('python TD645 terminal start...')

ports = []
for port in serial.tools.list_ports.comports():
    ports.append(port.name)
print(ports)
comPort = '/dev/ttyUSB1'

def getSendPgk645( address , data):
    res = [0x68]
    try:
        a = '000000000000'+ address
        a = a[-12:] 
        for i in range(6):
            v = int(a[2*(5-i):2*(6-i)],16)
            res.append(v)
        res.append(0x68)
        res.append(0x11)
        res.append(len(data))
        for i in range(len(data)): 
            res.append(data[i]+0x33) 

        cs = sum(res) & 0xff 
        print(cs)
        res.append(cs)
        res.append(0x16)
    except Exception as er:
        print(er)
    return res

addr = "440039000136"
#addr = "202012012147"
data3210 = [0,0,0,0]
pgk = bytearray(getSendPgk645(addr, data3210))
print(pgk.hex())

ports=['/dev/'+ports[0]]
for serPort in ports:
    try:
        comPort = '/dev/'+ serPort
        comPort =  serPort
        print(comPort)
        serConn = serial.Serial(comPort, 2400, parity=serial.PARITY_EVEN, timeout=2)
        isOpen = serConn.isOpen()
        print('ser:' , serConn , isOpen)
        sendBytes = bytearray(pgk)
        serConn.write(sendBytes)
        res =  serConn.readall()
        print(res.hex())
        serConn.close()
    except Exception as ee:
        print(ee)
"""
def serialExchange(self, dataList):
        with serial.Serial(self.comPort, 9600, parity=serial.PARITY_EVEN, timeout=2) as serialConn:
            if serialConn.isOpen():
                # 清洗执行控制电表报文命令
                serialConn.write(b''.join([binascii.a2b_hex(data) for data in dataList]))
                # 返回的数据，判断是否执行正常
                return {'success': True, 'data': re.findall(r'[0-9A-Z]{2}', binascii.b2a_hex(serialConn.readline()).decode().upper())} # 返回数据帧
            else:
                return {'success': False, 'description': '端口未打开'} 
"""
